package com.gitee.blogcase.dealyqueuecase.controller;

import com.gitee.blogcase.dealyqueuecase.utils.DateUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("redis/expired/key")
@AllArgsConstructor
public class RedisKeyExpiredController {
    private RedisTemplate redisTemplate;
    // Redis需要需要处理的Key前缀
    public static final String ORDER_TIMEOUT_PREFIX = "ORDERTIMEOUT-";
    // 过期秒数
    private final int defaultTimoutSecond = 10;

    /**
     * Redis保存订单号与过期事件
     * http://localhost:8022/redis/expired/key/send?orderId=100000001
     * http://localhost:8022/redis/expired/key/send?orderId=100000002
     * http://localhost:8022/redis/expired/key/send?orderId=100000003
     * http://localhost:8022/redis/expired/key/send?orderId=100000004
     * http://localhost:8022/redis/expired/key/send?orderId=100000005
     * @param orderId 订单编号
     */
    @GetMapping("/send")
    public String send(@RequestParam(value = "orderId") String orderId){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String key = ORDER_TIMEOUT_PREFIX + orderId;
        String value = orderId;
        long timeout = defaultTimoutSecond;
        TimeUnit seconds = TimeUnit.SECONDS;
        valueOperations.set(key,value,timeout, seconds);
        log.info("当前时间:[{}] 订单编号:[{}] Redis-Key:[{}] 超时秒数:[{}] ", DateUtil.getCuurentDateStr(),value,key,timeout);
        return "OK";
    }
}
